import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/visit_entity.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/my_refresh_list.dart';

class HumanVisitConfirmedPage extends StatefulWidget {
  @override
  _HumanVisitConfirmedPageState createState() =>
      _HumanVisitConfirmedPageState();
}

class _HumanVisitConfirmedPageState extends State<HumanVisitConfirmedPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  List<VisitInfo> dataList = [];
  bool isMore = false;
  int _page = 1;
  String _keyWord = '';

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    eventBus.on(Constant.eventHumanVisitSeaarch, (arg) {
      List target = arg;
      print(arg);
      if (arg.last == 1) {
        _keyWord = target.first;
        _onRefresh();
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return DeerListView(
      key: Key('_list'),
      itemCount: dataList.length,
      onRefresh: _onRefresh,
      loadMore: _loadMore,
      hasMore: isMore,
      itemBuilder: (_, index) {
        return Container(
          margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
          ),
          child: ExpansionTile(
            title: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Text(
                  '${dataList[index].preName ?? ''}',
                  style: TextStyles.textDark20,
                ),
                Gaps.hGap15,
                Text(
                  '${dataList[index].visitTime ?? ''}',
                  style: TextStyles.textGray16,
                ),
              ],
            ),
            children: [
              Gaps.vGap10,
              _item('来访机构：', '${dataList[index].orgName}'),
              Gaps.vGap10,
              _item('来访人数：', '${dataList[index].visitHumanNum}'),
              dataList[index].mealStandardName != null
                  ? Gaps.vGap10
                  : SizedBox(),
              dataList[index].mealStandardName != null
                  ? _item('餐饮标准：', '${dataList[index].mealStandardName}')
                  : SizedBox(),
              dataList[index].sourceNames != null ? Gaps.vGap10 : SizedBox(),
              dataList[index].sourceNames != null
                  ? _item('协调资源：', '${dataList[index].sourceNames}')
                  : SizedBox(),
              dataList[index].remark != null ? Gaps.vGap10 : SizedBox(),
              dataList[index].remark != null
                  ? _item('来访备注：', '${dataList[index].remark}')
                  : SizedBox(),
              Gaps.vGap10,
              _item('接待时间：', '${dataList[index].updatedDate ?? ''}'),
              Gaps.vGap10,
              _item('接待备注：', '${dataList[index].confirmRemark ?? ''}'),
              Gaps.vGap10,
              _item('接待确认：', '${dataList[index].confirmName ?? ''}'),
              Gaps.vGap12,
            ],
          ),
        );
      },
      // separatorBuilder: (_, index) => Gaps.midLine,
    );
  }

  Widget _item(String title, String content) {
    return Container(
      padding: EdgeInsets.only(left: 12, right: 12),
      width: double.infinity,
      child: Text.rich(TextSpan(children: [
        TextSpan(text: title, style: TextStyles.textGray14),
        TextSpan(text: content ?? '', style: TextStyles.textNormal14),
      ])),
    );
  }

  _fectData() {
    SVProgressHUD page = SVProgressHUD(context);
    var map = {
      'page': _page,
      'rows': 20,
      'validStatus': 1,
      'preNameLike': _keyWord,
      'sourceId': 2
    };
    print(map);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.visitRecordList}?${requestParams(map)}')
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            VisitListModel model = VisitListModel.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = (model.rows??[]).length == 20;
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              if (_page == 1) {
                /// 刷新
                setState(() {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                });
              }
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    _fectData();
  }

  Future _loadMore() async {
    _page++;
    _fectData();
  }
}
